package office.action.hr;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import office.action.hr.vo.TimingVo;
import office.bo.hr.impl.Timing;
import office.bo.person.Trip;
import office.service.person.IPersonService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import current.security.user.domain.User;
import current.security.user.manager.service.UserManagerService;
import platform.common.action.BaseAction;
import platform.util.DateUtil;

@Namespace("/timing")
@ParentPackage("struts-base")
@Controller("timingAction")
@Scope("prototype")
public class TimingAction extends BaseAction{
	private static final long serialVersionUID = 1L;
	private TimingVo timingVo;
	private List<TimingVo> listTimingVo = new ArrayList<TimingVo>();
	private Integer year = DateUtil.getYear();
	private Integer month = DateUtil.getMonth();
	private UserManagerService userManagerService;
	private String userId;
	private List<User> users ;
	@Resource
	private IPersonService personalServiceImpl;
	
	@Action(value="clock")
	public String clock(){
		Timing timing = null;
		try {
			timing = personalServiceImpl.getTimingById(timingVo.getId());
			//打卡时间只需要 yyyy-MM-dd HH:mm:ss 的后半部分
			String time = DateUtil.getDate().split(" ")[1];
			if(timing != null){
				if(timing.getType().equals("am")){
					if(DateUtil.compareTo(time, "09:01:00", "HH:mm:ss") >= 0){
						//超时不能打卡
						this.getAjaxMessagesJson().setMessage(false, "", "已经超过上班打开时间（9:00），不能签到！");
						return RESULT_AJAXJSON;
					}
					if(DateUtil.compareTo(time, "08:31:00", "HH:mm:ss") >= 0){
						//迟到
						timing.setFlag("-1");
					}else{
						timing.setFlag("0");
					}
				}else{
					if(DateUtil.compareTo(time, "23:01:00", "HH:mm:ss") >= 0){
						//超时不能打卡
						this.getAjaxMessagesJson().setMessage(false, "", "已经超过下班打卡时间（23:00），不能签到！");
						return RESULT_AJAXJSON;
					}
					if(DateUtil.compareTo(time, "17:30:00", "HH:mm:ss") <= 0){
						//早退
						timing.setFlag("-2");
					} else {
						timing.setFlag("0");
					}
				}
				timing.setClockTime(time);
				this.getAjaxMessagesJson().setMessage(true, "", "签到成功！");
			}
		} catch (Exception e) {
			this.getAjaxMessagesJson().setMessage(false, "", "签到失败！");
			log.error("", e);
		}
		return RESULT_AJAXJSON;
	}
	
	@Action(value="gotoClock",results={@Result(location="/pages/hr/clock.jsp")})
	public String gotoClock(){
		Trip trip = personalServiceImpl.getTripByUidAndDate(super.getUserId());
		if(trip != null){
			try {
				List<Timing> list = personalServiceImpl.getTimingByTrip(trip.getId().toString());
				if(list == null || list.size() == 0){
					// 公式是为了兼容以前的格式
					String gs = "yyyy-MM-dd";
					if(trip.getBeginDate().indexOf(" ") != -1 && trip.getBeginDate().indexOf(":") != -1){
						gs = "yyyy-MM-dd HH:mm:ss";
					}
					//计算起止时间的差
					double poor = DateUtil.timePoorDouble(trip.getBeginDate(), trip.getStopDate()!=null?trip.getStopDate():trip.getEndDate(),gs);
					int ipoor = (int) poor;
					for(int i = 0 ; i <= ipoor ; i ++){
						//判断第一天打卡的次数
						if( i == 0 ){
							//最新的时间格式
							if(trip.getBeginDate().indexOf(" ") != -1 && trip.getBeginDate().indexOf(":") != -1){
								String time = trip.getBeginDate().split(" ")[1];
								//开始时间在工作范围内则只需要晚上打卡即可
								if(DateUtil.compareTo(time, "09:01:00", "HH:mm:ss") >= 0 && DateUtil.compareTo(time, "17:30:00", "HH:mm:ss") <= 0){
									saveTiming(trip,"pm",i);
								//如果早于9点则需要打两次
								}else if(DateUtil.compareTo(time, "09:01:00", "HH:mm:ss") <= 0){
									saveTiming(trip,"am",i);
									saveTiming(trip,"pm",i);
								}
							//老时间格式
							}else{
								saveTiming(trip,"am",i);
								saveTiming(trip,"pm",i);
							}
						//判断最后一天的打卡次数
						}else if(i == ipoor){
							//最新的时间格式
							if(trip.getEndDate().indexOf(" ") != -1 && trip.getEndDate().indexOf(":") != -1){
								String time = trip.getEndDate().split(" ")[1];
								//结束时间在工作范围内则只需要早上打卡即可
								if(DateUtil.compareTo(time, "09:01:00", "HH:mm:ss") >= 0 && DateUtil.compareTo(time, "17:30:00", "HH:mm:ss") <= 0){
									saveTiming(trip,"am",i);
								//如果大于5:30则需要打卡两次
								}else if(DateUtil.compareTo(time, "17:30:00", "HH:mm:ss") >= 0){
									saveTiming(trip,"am",i);
									saveTiming(trip,"pm",i);
								}
							//老时间格式
							}else{
								saveTiming(trip,"am",i);
								saveTiming(trip,"pm",i);
							}
						//其他时间打两次卡
						}else{
							saveTiming(trip,"am",i);
							saveTiming(trip,"pm",i);
						}
					}
					list = personalServiceImpl.getTimingByTrip(trip.getId().toString());
				}
				for (Iterator<Timing> iterator = list.iterator(); iterator.hasNext();) {
					Timing timing = (Timing) iterator.next();
					TimingVo thisTimingVo = new  TimingVo();
					BeanUtils.copyProperties(thisTimingVo, timing);
					//旷工
					if(DateUtil.compareTo(thisTimingVo.getThisDate(), DateUtil.getDate("yyyy-MM-dd"), "yyyy-MM-dd") < 0 && thisTimingVo.getClockTime() == null){
						thisTimingVo.setFlag("-3");
					}
					//可以进行打卡
					if(DateUtil.compareTo(thisTimingVo.getThisDate(), DateUtil.getDate("yyyy-MM-dd"), "yyyy-MM-dd") == 0 && thisTimingVo.getFlag() == null){
						thisTimingVo.setIsClock("true");
					}
					listTimingVo.add(thisTimingVo);
				}
			} catch (Exception e) {
				log.error("", e);
			}
		}
		return "success";
	}
	
	public void saveTiming(Trip trip,String time,int i){
		User user = new User();
		user.setId(super.getUserId());
		Timing timing1 = new Timing();
		timing1.setThisDate(DateUtil.timeAdd(trip.getBeginDate(), i));
		timing1.setType(time);
		timing1.setUser(user);
		timing1.setTrip(trip);
		personalServiceImpl.saveTiming(timing1);
	}
	
	@Action(value="getAllClockByUid",results={@Result(location="/pages/hr/clockHistory.jsp")})
	public String getAllClockByUid(){
			try {
				if(userId == null){
					userId = super.getUserId();
				}
				if(getUserRoleName().equals("xzrsjl")){
					users = userManagerService.getAllActiveUser();
				}else{
					users = userManagerService.getUsersByAllDepartment(getUserDepartmentId());
				}
				List<Timing> list = personalServiceImpl.getAllTimingByUid(userId,DateUtil.getBegindate(year, month),DateUtil.getEnddate(year, month));
				for (Iterator<Timing> iterator = list.iterator(); iterator.hasNext();) {
					Timing timing = (Timing) iterator.next();
					TimingVo thisTimingVo = new  TimingVo();
					BeanUtils.copyProperties(thisTimingVo, timing);
					if(DateUtil.compareTo(thisTimingVo.getThisDate(), DateUtil.getDate("yyyy-MM-dd"), "yyyy-MM-dd") == 0){
						thisTimingVo.setIsClock("true");
					}
					if(DateUtil.compareTo(thisTimingVo.getThisDate(), DateUtil.getDate("yyyy-MM-dd"), "yyyy-MM-dd") < 0 && thisTimingVo.getClockTime() == null){
						thisTimingVo.setFlag("-3");
					}
					listTimingVo.add(thisTimingVo);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		return "success";
	}
	
//	@Action(value="getAllClock",results={@Result(location="/pages/hr/clockHistory.jsp")})
//	public String gotoAllClock(){
//		try {
//			List<Timing> list = personalServiceImpl.getAllTimingByDate(DateUtil.getBegindate(year, month),DateUtil.getEnddate(year, month));
//			for (Iterator<Timing> iterator = list.iterator(); iterator.hasNext();) {
//				Timing timing = (Timing) iterator.next();
//				TimingVo thisTimingVo = new  TimingVo();
//				BeanUtils.copyProperties(thisTimingVo, timing);
//				if(DateUtil.compareTo(thisTimingVo.getThisDate(), DateUtil.getDate("yyyy-MM-dd"), "yyyy-MM-dd") == 0){
//					thisTimingVo.setIsClock("true");
//				}
//				if(DateUtil.compareTo(thisTimingVo.getThisDate(), DateUtil.getDate("yyyy-MM-dd"), "yyyy-MM-dd") < 0 && thisTimingVo.getClockTime() == null){
//					thisTimingVo.setFlag("-3");
//				}
//				listTimingVo.add(thisTimingVo);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return "success";
//	}
	public IPersonService getPersonalServiceImpl() {
		return personalServiceImpl;
	}
	public void setPersonalServiceImpl(IPersonService personalServiceImpl) {
		this.personalServiceImpl = personalServiceImpl;
	}
	public TimingVo getTimingVo() {
		return timingVo;
	}
	public void setTimingVo(TimingVo timingVo) {
		this.timingVo = timingVo;
	}
	public List<TimingVo> getListTimingVo() {
		return listTimingVo;
	}
	public void setListTimingVo(List<TimingVo> listTimingVo) {
		this.listTimingVo = listTimingVo;
	}
	public Integer getYear() {
		return year;
	}
	public void setYear(Integer year) {
		this.year = year;
	}
	public Integer getMonth() {
		return month;
	}
	public void setMonth(Integer month) {
		this.month = month;
	}
	public String getUserId() {
		return userId;
	}
	public UserManagerService getUserManagerService() {
		return userManagerService;
	}
	public void setUserManagerService(UserManagerService userManagerService) {
		this.userManagerService = userManagerService;
	}
	public List<User> getUsers() {
		return users;
	}
	public void setUsers(List<User> users) {
		this.users = users;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
}
